package com.doraemon.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类：用于封装HTTP GET和POST请求的通用方法
 */
public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 5 * 1000; // 请求超时时间设置（单位：毫秒）

    /**
     * 发送GET请求
     * ---
     * @param url 请求地址
     * @param paramMap 请求参数的键值对
     * @return 返回响应结果的字符串形式
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建HttpClient对象，用于执行请求
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = ""; // 保存请求结果
        CloseableHttpResponse response = null;

        try {
            // 创建URI构造器，并添加参数
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key)); // 设置参数
                }
            }
            URI uri = builder.build(); // 构造完整的URI

            // 创建GET请求对象
            HttpGet httpGet = new HttpGet(uri);

            // 执行GET请求并接收响应
            response = httpClient.execute(httpGet);

            // 判断响应状态是否为200（OK），并获取响应内容
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭响应和客户端连接
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result; // 返回响应内容
    }

    /**
     * 发送POST请求（表单形式）
     * ---
     * @param url 请求地址
     * @param paramMap 请求参数的键值对
     * @return 返回响应结果的字符串形式
     * @throws IOException 抛出IO异常
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = ""; // 保存请求结果

        try {
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url);

            // 构造请求参数
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>(); // 存放参数的列表
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    // 将参数封装为键值对
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 设置表单数据为POST请求体
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            // 设置请求配置（超时时间等）
            httpPost.setConfig(builderRequestConfig());

            // 执行POST请求并接收响应
            response = httpClient.execute(httpPost);

            // 获取响应结果
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e; // 抛出异常
        } finally {
            try {
                response.close(); // 关闭响应
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString; // 返回响应内容
    }

    /**
     * 发送POST请求（JSON格式）
     * ---
     * @param url 请求地址
     * @param paramMap 请求参数的键值对
     * @return 返回响应结果的字符串形式
     * @throws IOException 抛出IO异常
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = ""; // 保存请求结果

        try {
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url);

            // 构造JSON格式的请求体
            if (paramMap != null) {
                JSONObject jsonObject = new JSONObject(); // 创建JSON对象
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue()); // 添加参数
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8"); // 设置请求体内容
                entity.setContentEncoding("utf-8"); // 设置请求编码
                entity.setContentType("application/json"); // 设置数据类型为JSON
                httpPost.setEntity(entity); // 将请求体设置到POST请求中
            }

            // 设置请求配置（超时时间等）
            httpPost.setConfig(builderRequestConfig());

            // 执行POST请求并接收响应
            response = httpClient.execute(httpPost);

            // 获取响应结果
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e; // 抛出异常
        } finally {
            try {
                response.close(); // 关闭响应
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString; // 返回响应内容
    }

    /**
     * 构造请求配置
     * ---
     * @return 返回RequestConfig对象
     */
    private static RequestConfig builderRequestConfig() {
        // 设置连接超时时间、请求超时时间和数据读取超时时间
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC) // 连接超时时间
                .setConnectionRequestTimeout(TIMEOUT_MSEC) // 请求超时时间
                .setSocketTimeout(TIMEOUT_MSEC) // 数据读取超时时间
                .build();
    }

}